package com.szrt.session;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.szrt.listener.ScottServletContextListener;
import com.szrt.session.entity.UserEntity;


@WebServlet(name="userController",value="/central/user.do")
public class UserController extends  HttpServlet {

	private static final long serialVersionUID = -1245890152557129501L;
	
	
	
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse resp) 
			throws ServletException, IOException {
		
		
		System.out.println("UserController "+request);
		//上下文  web application =web 应用  app=application
		ServletContext application = request.getSession().getServletContext();
		System.out.println(application);
		
		//取  放
		
		Set<String> userSets = CounterDTO.getCounters();
		
		userSets.add(request.getParameter("username"));
		
		int size  = userSets.size();
		
		application.setAttribute("user", size);
		
		
		String method = request.getParameter("method");
		
		if("invalidate".equals(method)){
			HttpSession session = request.getSession();
			session.invalidate();
			return;
		}

		
		//处理  post请求乱码问题 前台传给后台的数据
		//request.setCharacterEncoding("utf-8");
		
		String username = request.getParameter("username");
		System.out.println(username);
		
		
		
		//一旦用户登陆  给用户1个篮子   Session getSession会马上创建一个 session对象
		HttpSession session = request.getSession();
		System.out.println(session.getClass().getName());
		
		String id  = session.getId();
		
		System.out.print(id);
		
		
		UserEntity user = new UserEntity();
		user.setId(Integer.parseInt(request.getParameter("id")));
		user.setUsername(request.getParameter("username"));
		user.setPassword(request.getParameter("password"));
		
		System.err.println(user);
		
		
		session.setAttribute("entity", user);
		
		
		System.out.println("进入service方法....");
		
		Gson json = new Gson();
		
		Map<String, Object> map = new HashMap<String, Object>();
		/*if("老黄".equals(request.getParameter("username"))){
			map.put("code", "200");
		}else{
			map.put("code", "404");
		}*/
		
		map.put("code", "200");
		map.put("entity", user);
		resp.getWriter().write(json.toJson(map));
		
		
	}
	

}
